//⻓度最⼩的⼦数组（medium）
//https://leetcode.cn/problems/minimum-size-subarray-sum/
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) 
    {
        int sum = 0;
        int len = INT_MAX;
        int left = 0;
        int right = 0;
        while(right < nums.size())
        {
            sum += nums[right];
            while(sum >= target)
            {
                len = min(len,right - left + 1);
                sum -= nums[left];
                left++;
            }

            right++;
        }
        return len == INT_MAX ? 0 : len;
    }
};

//⽆重复字符的最⻓⼦串
//https://leetcode.cn/problems/longest-substring-without-repeating-characters/
class Solution {
public:
    int lengthOfLongestSubstring(string s)
    {
        int hash[128] = {0};
        int left = 0;
        int right = 0;
        int len = 0;
        while(right < s.size())
        {
            hash[s[right]]++;
            while(hash[s[right]] > 1)
                hash[s[left++]]--;
            len = max(len,right - left + 1);
            right++;
        }

        return len;
    }
};

//最⼤连续 1 的个数 III
//https://leetcode.cn/problems/max-consecutive-ones-iii/
class Solution 
{
public:
    int longestOnes(vector<int>& nums, int k) 
    {
        int zero = 0;
        int left = 0;
        int right = 0;
        int len = 0;
        while(right < nums.size())
        {
            if(nums[right] == 0) zero++;
            while(zero > k)
            {
                if(nums[left] == 0) zero--;
                left++;
            }
            len = max(len,right - left + 1);
            right++;
        }  
        return len;
    }
};

//将 x 减到 0 的最⼩操作数
//https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/
public:
    int minOperations(vector<int>& nums, int x) 
    {
        int sum = 0;
        for(auto e :nums)sum+=e;
        int target = sum - x;
        if(target < 0) return -1;

        int ret = -1;
        int left = 0;
        int right = 0;
        int tem = 0;
        while(right < nums.size())
        {
            tem += nums[right];
            while(tem > target)
                tem -= nums[left++];
            if(tem == target)
            {
                ret = max(ret,right - left + 1);
            }
            right++;
        }
        if(ret == -1) return -1;
         return nums.size() - ret;
    }
};